package com.cq.hd.app.biz;

import com.alibaba.fastjson.JSON;
import com.cq.hd.app.config.WxPubConfig;
import com.cq.hd.app.vo.UserSubscribeStateVo;
import com.cq.hd.app.vo.WithdrawalPreVo;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.constant.RedisKeyConstant;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.BusinessInfo;
import com.cq.hd.common.entity.UserInfo;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.TbAppUserApi;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.TbWxSubscribeRecordApi;
import com.cq.hd.member.api.dto.AppUserPwdUpdateDto;
import com.cq.hd.member.api.vo.AppUserVo;
import com.cq.hd.member.api.vo.BusinessPageVo;
import com.cq.hd.member.api.vo.WxSubscribeRecordVo;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.TbOrderSettleBillApi;
import com.cq.hd.order.api.dto.OrderItemDto;
import com.cq.hd.order.api.dto.OrderSettleBillDto;
import com.cq.hd.order.api.vo.OrderEstimateCommissionVo;
import com.cq.hd.order.api.vo.OrderItemVo;
import com.cq.hd.order.api.vo.OrderSettleBillVo;
import com.cq.hd.order.api.vo.OrderVo;
import com.cq.hd.system.api.TbWithdrawalConfigApi;
import com.cq.hd.system.api.vo.WithdrawalConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class UserBiz {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TbAppUserApi appUserApi;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbOrderItemApi orderItemApi;

    @Autowired
    private TbOrderSettleBillApi orderSettleBillApi;

    @Autowired
    private TbWithdrawalConfigApi withdrawalConfigApi;

    @Autowired
    private TbWxSubscribeRecordApi wxSubscribeRecordApi;

    @Autowired
    private WxPubConfig wxPubConfig;
    @Autowired
    private TbOrderApi tbOrderApi;

    public UserInfo getUserInfo(AppLoginUser appLoginUser) {
        UserInfo userInfo = new UserInfo();
//        String userInfoRedis = redisUtil.get(String.format(RedisKeyConstant.USER_INFO_KEY, appLoginUser.getUserId()));
//        if (!StringUtils.isNullOrEmpty(userInfoRedis)) {
//            userInfo = JSON.parseObject(userInfoRedis, UserInfo.class);
//            return userInfo;
//        }

        // 通过userId查询用户信息
        AppUserVo appUserVo = appUserApi.getById(appLoginUser.getUserId()).unpack();
        if (appUserVo == null || appUserVo.getState() == 2) {
            Throw.isBusinessException(ResponseEnums.USER_NOT_FOUND);
        }
        BeanUtils.copyProperties(appUserVo, userInfo);
        userInfo.setPwdSetState(!StringUtils.isBlank(appUserVo.getLoginPass()));

        // 通过userId查询商家信息
        BusinessPageVo businessPageVo = businessApi.getByUserId(appLoginUser.getUserId()).unpack();
        if (businessPageVo != null) {
            BusinessInfo businessInfo = new BusinessInfo();
            BeanUtils.copyProperties(businessPageVo, businessInfo);
            userInfo.setBusinessInfo(businessInfo);
        }

        return userInfo;
    }

    public Result<Boolean> updatePwd(AppUserPwdUpdateDto appUserPwdUpdateDto) {
        return appUserApi.updatePwd(appUserPwdUpdateDto);
    }

    public WithdrawalPreVo preWithdrawal(AppLoginUser appLoginUser) {
        // 可提佣金
        BigDecimal commissionAmt = BigDecimal.ZERO;
        // 今日预估佣金 = 今天产生的推广订单预计可得佣金
        BigDecimal dayEstimateAmt = BigDecimal.ZERO;
        // 本月预估佣金 = 本月产生的推广订单预计可得佣金
        BigDecimal monthEstimateAmt = BigDecimal.ZERO;
        // 累计佣金 = 累计已结算的佣金
        BigDecimal totalSettleAmt = BigDecimal.ZERO;

        Long userId = appLoginUser.getUserId();
        AppUserVo appUserVo = appUserApi.getById(userId).unpack();
        // 是否是经纪人(1-不是，2-是)
        if (appUserVo != null && appUserVo.getAgentState() == 2) {
            commissionAmt = appUserVo.getCommissionAmt();

//            LocalDate nowLocalDate = LocalDate.now();
//            LocalDateTime startNowLocalDateTime = LocalDateUtil.toLocalDateTime(LocalDateUtil.toLocalDateToString(nowLocalDate, Constant.YYYY_MM_DD) + " 00:00:00",
//                    Constant.YYYY_MM_DD_HH_MM_SS);
//            LocalDateTime endNowLocalDateTime = LocalDateUtil.toLocalDateTime(LocalDateUtil.toLocalDateToString(nowLocalDate, Constant.YYYY_MM_DD) + " 23:59:59",
//                    Constant.YYYY_MM_DD_HH_MM_SS);
//
//            // 本月1号
//            String firstDayOfMonthStartStr = LocalDateUtil.toLocalDateToString(nowLocalDate.with(TemporalAdjusters.firstDayOfMonth()), Constant.YYYY_MM_DD) + " 00:00:00";
//            // 本月最后一天
//            String lastDayOfMonthEndStr = LocalDateUtil.toLocalDateToString(nowLocalDate.with(TemporalAdjusters.lastDayOfMonth()), Constant.YYYY_MM_DD) + " 23:59:59";

//            // 查询本月的待核销/已核销的当前用户所分销的订单项列表
//            OrderItemDto orderItemDto = new OrderItemDto();
//            orderItemDto.setAgentId(userId);
//            orderItemDto.setStartOrderTime(firstDayOfMonthStartStr);
//            orderItemDto.setEndOrderTime(lastDayOfMonthEndStr);
//            orderItemDto.setSubOrderStates(Arrays.asList(SubOrderStateEnum.WAIT_VERIFY.getValue(), SubOrderStateEnum.VERIFIED.getValue()));
//            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
//            if (!CollectionUtils.isEmpty(orderItemVos)) {
//                for (OrderItemVo orderItemVo : orderItemVos) {
//                    BigDecimal currCommissionAmt = orderItemVo.getCommissionAmt();
//                    LocalDateTime orderTime = orderItemVo.getOrderTime();
//                    // 判断是否是今天的订单
//                    if (orderTime.compareTo(startNowLocalDateTime) >= 0 && orderTime.compareTo(endNowLocalDateTime) <= 0) {
//                        dayEstimateAmt = dayEstimateAmt.add(currCommissionAmt);
//                    }
//
//                    monthEstimateAmt = monthEstimateAmt.add(currCommissionAmt);
//                }
//            }
            OrderEstimateCommissionVo orderEstimateCommissionVo = tbOrderApi.getOrderEstimateCommission(userId).unpack();
            if (orderEstimateCommissionVo.getTodayEstimateCommissionAmt() != null) {
                dayEstimateAmt = orderEstimateCommissionVo.getTodayEstimateCommissionAmt();
            }
            if (orderEstimateCommissionVo.getMonthEstimateCommissionAmt() != null) {
                monthEstimateAmt = orderEstimateCommissionVo.getMonthEstimateCommissionAmt();
            }

            OrderSettleBillDto orderSettleBillDto = new OrderSettleBillDto();
            orderSettleBillDto.setTradeType(OrderSettleBillTradeTypeEnum.COMMISSION_AMT.getValue());
            orderSettleBillDto.setAgentId(userId);
            List<OrderSettleBillVo> orderSettleBillVos = orderSettleBillApi.listByDto(orderSettleBillDto).unpack();
            if (!CollectionUtils.isEmpty(orderSettleBillVos)) {
                for (OrderSettleBillVo orderSettleBillVo : orderSettleBillVos) {
                    totalSettleAmt = totalSettleAmt.add(orderSettleBillVo.getTradeAmt());
                }
            }
        }

        // 查询提现说明
        String description = "";
        WithdrawalConfigVo withdrawalConfigVo = withdrawalConfigApi.details(WithdrawalConfigUserTypeEnum.AGENT_COMMISSION.getValue(), FinancialAccountTypeEnum.SELF.getValue()).unpack();
        if (withdrawalConfigVo != null) {
            description = withdrawalConfigVo.getDescription();
        }

        WithdrawalPreVo withdrawalPreVo = new WithdrawalPreVo();
        withdrawalPreVo.setCommissionAmt(commissionAmt);
        withdrawalPreVo.setDayEstimateAmt(dayEstimateAmt);
        withdrawalPreVo.setMonthEstimateAmt(monthEstimateAmt);
        withdrawalPreVo.setTotalSettleAmt(totalSettleAmt);
        withdrawalPreVo.setDescription(description);
        return withdrawalPreVo;
    }

    public UserSubscribeStateVo getSubscribeState(AppLoginUser appLoginUser) {
        Long userId = appLoginUser.getUserId();

        boolean subscribeState = true;
        Object subscribeCache = redisUtil.hGet(RedisKeyConstant.WX_PUB_SUBSCRIBE_KEY, String.valueOf(userId));
        if (subscribeCache == null) {
            WxSubscribeRecordVo wxSubscribeRecordVo = wxSubscribeRecordApi.getByUserId(userId).unpack();
            if (wxSubscribeRecordVo != null) {
                redisUtil.hmSet(RedisKeyConstant.WX_PUB_SUBSCRIBE_KEY, String.valueOf(userId),
                        LocalDateUtil.toLocalDateTimeToString(wxSubscribeRecordVo.getSubscribeTime(), Constant.YYYY_MM_DD_HH_MM_SS));
            }

            subscribeState = false;
        }

        UserSubscribeStateVo userSubscribeStateVo = new UserSubscribeStateVo();
        userSubscribeStateVo.setSubscribeState(subscribeState);
        userSubscribeStateVo.setWxPubCodeUrl(Constant.WX_PUB_SUBSCRIBE_CODE_URL);

        return userSubscribeStateVo;
    }
}
